import { Component, OnInit } from '@angular/core';
import { LoginService } from '../../login/common-service/login.service';
import { ProjectService } from '../../shared-property-resource/service/project.service';
import { Router } from '@angular/router';
import { CRUD_MODE } from '../../shared/config/app-settings';
import * as _ from 'lodash';
import { SettingsService } from '../../shared-property-resource/service/settings';
import { DomSanitizer } from '@angular/platform-browser';
import { NgProgress } from 'ngx-progressbar';
import { NgxSpinnerService } from 'ngx-spinner';
@Component({
  selector: 'app-propertyLists',
  templateUrl: './propertyLists.component.html',
  styleUrls: ['./propertyLists.component.css']
})
export class ProeprtyListsComponent implements OnInit {

  queryFilter = {};
  propertyLists: any[];
  sortedFeatures: any[];
  featureDict: any[];
  featuresProjects: any;
  typedProjects: any;
  types: any = [];
  cities2: Array<any> = [];
  selectedCities2: any[];
  mapShow: boolean = false;
  searchText: string = "";
  currentUser: string = "";
  cTab: number;
  constructor( private loginService: LoginService, 
    private projectService: ProjectService, 
    private settingsService:SettingsService,
    private _sanitizer: DomSanitizer,
    private router: Router,
    private ngProgress: NgProgress,
    private spinner: NgxSpinnerService) {
     }

  ngOnInit() {
    try {
        if (sessionStorage.getItem('propertyLists')) {
            this.propertyLists = (Array)(sessionStorage.getItem('propertyLists'));
        } else {
            this.propertyLists = null;
        }
        if (this.propertyLists === null) {
            this.spinner.show();
            this.loadPropertyLists(this.queryFilter);
        } else {
            this.propertyLists = JSON.parse(this.propertyLists.toString());
            this.categoryProjectsByType(this.propertyLists);
            this.searchText = sessionStorage.getItem('searchText');
        }
    } catch (err) {
        this.spinner.show();
        this.loadPropertyLists(this.queryFilter);
    }
  }

  // Zhan: Handle tabs. Only load tab when activated
  handleChange(e) {
    this.cTab = e.index;
  }
  loadPropertyLists(filter?) {
    this.settingsService.getAll().subscribe(
      res => {
        this.featureDict = res;
        this.projectService.getAllPropertyLists(filter).subscribe(
          (res) => {
            this.propertyLists =  _.filter(res, (project)=>project['status'] !== 'inactive');
            this.propertyLists =_.orderBy(this.propertyLists, ['featured', 'updateTime'],['desc', 'desc']);
            this.categoryProjectsByType(this.propertyLists);
            this.spinner.hide();
            sessionStorage.setItem('propertyLists', JSON.stringify(this.propertyLists));
            // let arr1:any[] = _.chain(this.propertyLists).map('featureId').value();
            // this.sortedFeatures = _.uniq(arr1);
          })
      }
    );
  }

  getFeatureNameById(Id){
    let intId = +Id;
    let f = _.find(this.featureDict, (feature)=>{ return feature['id'] === intId});
    return f? f.name: '';
  }

 
  getProjectsByFeatureId(featureId){
    return this.featuresProjects[featureId];
  }


  // getProjectKeys(){
  //   console.log("keys {}",_.keys(this.featuresProjects));
  //   return _.keys(this.featuresProjects);
  // }

  // categoryByFeature(projects) {
  //   this.featuresProjects = {};
  //   _.each(projects, (project) => {
  //     let fId = project['featureId'];
  //     if (_.has(this.featuresProjects, fId)) {
  //       this.featuresProjects[fId].push(project);
  //     } else {
  //       this.featuresProjects[fId] = [project];
  //     }
  //   });
  //   console.log("feature projects",this.featuresProjects);
  // };

  categoryProjectsByType(projects){
    let categoryProj = {};
    _.each(projects, (project)=>{
      let type = project['type'] || 'Others';
      
      if (project['priceRange']) {
        if (project['priceRange'].indexOf('-') !== -1) {
          project['priceRange'] = project['priceRange'].replace(/\B(?=(\d{3})+(?!\d))/g, ','); //Zhan: Insert commar between number to make it looks better
        }
      }
      
      if (_.has(categoryProj, type)) {
        categoryProj[type].push(project);
      } else {
        categoryProj[type] = [project];
        this.types.push(type);
      }
    });
    this.typedProjects = {};
    _.each(categoryProj, (projects, type) =>{
    
      this.typedProjects[type]=_.orderBy(projects, ['featureId'],['desc']);
      
    })
    console.log("typedProjects {}",this.typedProjects);
    console.log("types {}",this.types);
  }



  //utils
  getFullAddress(item) {
    return this.projectService.getFullAddress(item);
  }

  logoStyle() {

    return "{'background':'url(https://lwphoenix.blob.core.windows.net/files/images/upload/0003895_thumb.jpeg) center'; 'background-size':'100% 100%'; 'width':'100%'; 'height':0; 'padding-bottom':59.25%;}";
  }

  getLogo(item) {
    return `url(${this.projectService.getLogo(item)}) center`;
  }

  goToProjectDetail(project) {
    this.router.navigate(['/agent/shared/project-detail/' + project.id], { queryParams: { mode: CRUD_MODE.VIEW } });
  }




}
